package com.common.liblinphonesdk.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.common.liblinphonesdk.BuildConfig;
import com.common.liblinphonesdk.R;

import org.linphone.LinphoneManager;
import org.linphone.LinphoneService;
import org.linphone.call.CallOutgoingActivity;
import org.linphone.core.AccountCreator;
import org.linphone.core.AuthInfo;
import org.linphone.core.Call;
import org.linphone.core.ChatMessage;
import org.linphone.core.ChatRoom;
import org.linphone.core.Core;
import org.linphone.core.CoreListenerStub;
import org.linphone.core.PayloadType;
import org.linphone.core.ProxyConfig;
import org.linphone.core.Reason;
import org.linphone.core.RegistrationState;
import org.linphone.core.TransportType;
import org.linphone.core.tools.DeviceUtils;
import org.linphone.settings.LinphonePreferences;
import org.linphone.utils.LinphoneHelper;
import org.linphone.utils.Params;
import org.linphone.utils.VoipUtil;

import static android.content.Intent.ACTION_MAIN;


public class MainActivity extends AppCompatActivity {
    private Handler mHandler;
    private ServiceWaitThread mServiceThread;

    AccountCreator mAccountCreator;
    private CoreListenerStub mListener;

    private EditText edit_domain;
    private EditText edit_username;
    private EditText edit_pwd;
    private EditText edit_to;

    private TextView mStatusText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        edit_domain = findViewById(R.id.domain);
        edit_username = findViewById(R.id.username);
        edit_pwd = findViewById(R.id.password);
        edit_to = findViewById(R.id.to);
        mStatusText = findViewById(R.id.status_text);
        edit_domain.setText("47.101.133.144:5060");
        edit_pwd.setText("123456");
        edit_username.setText("9001");
//        edit_to.setText("9002");
        checkPermission();
        mHandler = new Handler();
        Params.MAIN_ACTIVITY = this.getClass().getName();
        if (LinphoneService.isReady()) {
            onServiceReady();
        } else {
            // start linphone as background
            VoipUtil.startService(this);
            mServiceThread = new ServiceWaitThread();
            mServiceThread.start();
        }


        mListener =
                new CoreListenerStub() {
                    @Override
                    public void onRegistrationStateChanged(
                            Core lc, ProxyConfig proxy, RegistrationState state, String smessage) {
                        if (state == RegistrationState.Ok) {
                            Toast.makeText(MainActivity.this, smessage, Toast.LENGTH_SHORT).show();
                            VoipUtil.startTalk("10003");
                        }

                        if (lc.getProxyConfigList() == null) {
                            mStatusText.setText(getString(R.string.no_account));
                        }

                        if (lc.getDefaultProxyConfig() != null
                                && lc.getDefaultProxyConfig().equals(proxy)) {

                            mStatusText.setText(getStatusIconText(state));
                        } else if (lc.getDefaultProxyConfig() == null) {

                            mStatusText.setText(getStatusIconText(state));
                        }
                        Log.e("-----", "AAAA-- " + proxy.getIdentityAddress().asString() + "----" + smessage);
                    }

                };

    }


    public void call(View view) {
        String callName = edit_to.getText().toString().trim();
        VoipUtil.outgoing(callName, false);
    }

    public void video(View view) {
        String callName = edit_to.getText().toString().trim();
        VoipUtil.outgoing(callName, true);
    }

    public void login(View v) {
        String username = edit_username.getText().toString();
        String ped = edit_pwd.getText().toString();
        String domain = edit_domain.getText().toString();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this,"输入账号",Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(ped)) {
            Toast.makeText(this,"输入密码",Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(domain)) {
            Toast.makeText(this,"输入域名",Toast.LENGTH_SHORT).show();
            return;
        }
        VoipUtil.login(domain, username, ped);
    }


    private void onServiceReady() {


        mHandler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "loaded", Toast.LENGTH_SHORT).show();
                        initStatusText();
                        //设置音频码率
//                        Core core = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
//                        if(core!=null){
//                            PayloadType[] payloadTypes = core.getAudioPayloadTypes();
//                            for(PayloadType type : payloadTypes){
//                                if(TextUtils.equals(type.getMimeType().toLowerCase(),"opus")){
//                                    type.enable(true);
//                                }else{
//                                    type.enable(false);
//                                }
//                            }
//                        }
                        VoipUtil.startTalk("10004");
                    }
                },
                500);


        LinphoneManager.getInstance().changeStatusToOnline();
    }

    private class ServiceWaitThread extends Thread {
        public void run() {
            while (!LinphoneService.isReady()) {
                try {
                    sleep(30);
                } catch (InterruptedException e) {
                    throw new RuntimeException("waiting thread sleep() has been interrupted");
                }
            }
            mHandler.post(
                    new Runnable() {
                        @Override
                        public void run() {
                            onServiceReady();
                        }
                    });
            mServiceThread = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!LinphoneService.isReady()) {
            startService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
        if (lc != null) {
            lc.removeListener(mListener);
        }
    }

    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            //进入到这里代表没有权限.
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE) ||
                    ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
                    ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO) ||
                    ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) ||
                    ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)
                    ) {
                //已经禁止提示了
                Toast.makeText(MainActivity.this, "您已禁止该权限，需要重新开启。", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CALL_PHONE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.RECORD_AUDIO,
                                Manifest.permission.CAMERA,
                                Manifest.permission.READ_CONTACTS
                        },
                        1000);

            }

        }
    }

    private String getStatusIconText(RegistrationState state) {


        try {
            if (state == RegistrationState.Ok
                    && LinphoneManager.getLcIfManagerNotDestroyedOrNull()
                    .getDefaultProxyConfig()
                    .getState()
                    == RegistrationState.Ok) {
                return getString(R.string.status_connected);
            } else if (state == RegistrationState.Progress) {
                return getString(R.string.status_in_progress);
            } else if (state == RegistrationState.Failed) {
                return getString(R.string.status_error);
            } else {
                return getString(R.string.status_not_connected);
            }
        } catch (Exception e) {
            org.linphone.core.tools.Log.e(e);
        }

        return getString(R.string.status_not_connected);
    }

    private void initStatusText() {
        Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
        if (lc != null) {
            lc.addListener(mListener);
            ProxyConfig lpc = lc.getDefaultProxyConfig();
            if (lpc != null) {
                mListener.onRegistrationStateChanged(lc, lpc, lpc.getState(), null);
            }

            // We are obviously connected
            if (lc.getDefaultProxyConfig() == null) {
                mStatusText.setText(getString(R.string.no_account));
            } else {
                mStatusText.setText(getStatusIconText(lc.getDefaultProxyConfig().getState()));
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        VoipUtil.stopService(this);
    }
}
